<?php



namespace app\admin\controller\shopro;



use think\Db;

use addons\shopro\library\Tree;

use app\admin\model\shopro\Banner as BannerModel;
use fast\Tree as FastTree;


/**

 * 轮播图

 */

class Banner extends Common

{



    protected $noNeedRight = ['select'];

    protected $model = null;

    protected $category = null;

    public function _initialize()

    {

        parent::_initialize();
        $this->category = new \app\admin\model\shopro\Category;

		$this->tree = FastTree::instance();
        $this->tree->init(collection($this->category->order('weigh desc,id desc')->select())->toArray(), 'parent_id');
        $this->categoryList = $this->tree->getTreeList($this->tree->getTreeArray(0), 'name');
        $this->model = new BannerModel;
        $this->view->assign("categoryList", $this->model);
        $this->view->assign("statusList", $this->model->getStatusList());

    }





    /**

     * 服务保障列表

     *

     * @return \think\Response

     */

    public function index()

    {

        if (!$this->request->isAjax()) {

            return $this->view->fetch();

        }

        

        $banner = $this->model->sheepFilter()->order('weigh', 'desc')->order('id', 'desc')->select();
        $banner = collection($banner)->toArray();
        foreach ($banner as $k => &$v) {
            if ($v['category_id'] == 0) {
                $v['category_name'] = '首页';
            } else {
                $v['category_name'] = $this->category->where('id', $v['category_id'])->value('name');
            }
            
        }

        $total = count($banner);

        $result = array("total" => $total, "rows" => $banner, "categoryList" => $this->categoryList);

        return json($result);

    }









    /**

     * 添加服务保障

     *

     * @return \think\Response

     */

    public function add()

    {

        if (!$this->request->isAjax()) {

            return $this->view->fetch();

        }

        $params = $this->request->post("row/a");

        $this->svalidate($params, ".add");

        Db::transaction(function () use ($params) {

            $this->model->allowField(true)->save($params);

        });

        $this->success('保存成功');

    }










    /**

     * 修改轮播图

     *

     * @return \think\Response

     */

    public function edit($ids = null)

    {

        if (!$this->request->isPost()) {
            $row = $this->model->get($ids);
            $this->view->assign("row", $row);
            return $this->view->fetch();

        }



        $params = $this->request->post("row/a");

        $this->svalidate($params, ".edit");

        $banner = $this->model->where('id', $ids)->find();

        if (!$banner) {

            $this->error(__('No Results were found'));

        }

        Db::transaction(function () use ($banner, $params) {

            $banner->allowField(true)->save($params);

        });

        $this->success('更新成功');

    }







    /**

     * 删除服务标签

     *

     * @param string $id 要删除的服务保障列表

     * @return void

     */

    public function delete($id)

    {

        if (empty($id)) {

            $this->error(__('Parameter %s can not be empty', 'id'));

        }



        $list = $this->model->with('children')->where('id', 'in', $id)->select();

        $result = Db::transaction(function () use ($list) {

            $count = 0;

            foreach ($list as $item) {

                if ($item->children) {

                    $this->error('请先删除子分类');

                }

                $count += $item->delete();

            }



            return $count;

        });



        if ($result) {

            $this->success('删除成功', null, $result);

        } else {

            $this->error(__('No rows were deleted'));

        }

    }





    /**

     * 获取所有服务列表

     *

     * @return \think\Response

     */

    public function select()

    {

        if (!$this->request->isAjax()) {

            return $this->view->fetch();

        }



        $categories = (new Tree(function () {

            // 组装搜索条件，排序等

            return $this->model->field("id, name, parent_id, status, weigh")->normal()

                ->order('weigh', 'desc')->order('id', 'asc');

        }))->getTree(0);



        $this->success('获取成功', null, $categories);

    }







    private function createOrEditCategory($categories, $parent_id)

    {

        foreach ($categories as $key => $data) {

            $data['parent_id'] = $parent_id;



            if (isset($data['id']) && $data['id']) {

                $category = $this->model->find($data['id']);

                if (!$category) {

                    $this->error(__('No Results were found'));

                }

                if (isset($data['deleted']) && $data['deleted'] == 1) {

                    $category->delete();

                } else {

                    $category->name = $data['name'];

                    $category->parent_id = $data['parent_id'];

                    $category->image = $data['image'];

                    $category->description = $data['description'] ?? null;

                    $category->status = $data['status'];

                    $category->weigh = $data['weigh'];

                    $category->save();

                }

            } else {

                if (!isset($data['deleted']) || !$data['deleted']) {

                    $category = new BannerModel;

                    $category->name = $data['name'];

                    $category->parent_id = $data['parent_id'];

                    $category->image = $data['image'];

                    $category->description = $data['description'] ?? null;

                    $category->status = $data['status'];

                    $category->weigh = $data['weigh'];

                    $category->save();

                    $data['id'] = $category->id;

                }

            }



            if (isset($data['children']) && !empty($data['children']) && isset($data['id'])) {

                $this->createOrEditCategory($data['children'], $data['id']);

            }

        }

    }

}

